<?php

namespace liketp;

use liketp\foundation\MacroTrait;

class Request
{
    protected $app;

    protected $header = [];
    protected $server = [];

    protected $get = [];
    protected $post = [];
    protected $put = [];
    protected $delete = [];
    protected $file = [];
    protected $input = [];

    protected $cookie = [];
    protected $session = [];
    protected $route = [];

    protected $env = [];
    protected $request = [];

    protected $controller = '';
    protected $action = '';

    protected $varPathinfo = 's';
    protected $varMethod = '_method';
    protected $varAjax = '_ajax';
    protected $varPjax = '_pjax';

    /**
     * 可能的值
     * text/plain, text/html, text/css, text/javascript, application/javascript
     * application/json; charset=utf-8
     * application/x-www-form-urlencoded, multipart/form-data
     * application/xml, text/xml
     * image/jpep, image/png, image/gif, application/pdf, application/octet-stream
     */
    protected $mimeTypeList = [
        'xml'   => 'application/xml,text/xml,application/x-xml',
        'json'  => 'application/json,text/x-json,application/jsonrequest,text/json',
        'js'    => 'text/javascript,application/javascript,application/x-javascript',
        'css'   => 'text/css',
        'rss'   => 'application/rss+xml',
        'yaml'  => 'application/x-yaml,text/yaml',
        'atom'  => 'application/atom+xml',
        'pdf'   => 'application/pdf',
        'text'  => 'text/plain',
        'image' => 'image/png,image/jpg,image/jpeg,image/pjpeg,image/gif,image/webp,image/*',
        'csv'   => 'text/csv',
        'html'  => 'text/html,application/xhtml+xml,*/*',
    ];

    use MacroTrait;

    public function __construct(App $app)
    {
        $this->app = $app;
        $this->init();
    }


    //------------------------------------------------ setXXX
    public function setWholeCookie(array $cookie = [])
    {
        $this->cookie = $cookie;
    }

    public function setCookie(string $key, ?string $value = null)
    {
        if (is_null($value)) {
            unset($this->cookie[$key]);
        } else {
            $this->cookie[$key] = $value;
        }
    }

    public function setRoute(string $key, ?string $value = null)
    {
        if (is_null($value)) {
            unset($this->route[$key]);
        } else {
            $this->route[$key] = $value;
        }
    }

    public function setRouteVars(array $vars, bool $merge = false)
    {
        if ($merge) $vars = array_merge($this->route, $vars);
        $this->route = $vars;
    }


    //------------------------------------------------ getXXX
    public function controller(bool $original = false)
    {
        $controllerSlice = explode('.', $this->controller);
        $controller = array_pop($controllerSlice);
        $controller = $original ? $controller : str_to_camel($controller, true);
        $controllerSlice[] = $controller;
        return implode('.', $controllerSlice);
    }

    public function action(bool $original = false)
    {
        return $original ? $this->action : str_to_camel($this->action, false);
    }

    public function header(?string $name = null, ?string $default = null)
    {
        if (is_null($name)) return $this->header;

        $name = str_replace('-', '_', strtolower($name));
        $fullName = strpos($name, 'http_') === 0 ? $name : 'http_' . $name;

        return $this->header[$name] ?? ($this->header[$fullName] ?? $default);
    }

    public function server(?string $key = null, ?string $default = null)
    {
        if (is_null($key)) return $this->server;

        $key = strtoupper($key);
        $keys = explode('|', $key);
        $val = null;

        foreach ($keys as $k) {
            $k = trim($k);
            $val = $this->server[$k] ?? null;
            if (isset($this->server[$k])) break;
        }

        return $val ?? $default;
    }


    //------------------------------------------------ is XXX
    public function checkRequestMethod(string $expect): bool
    {
        return $this->method() == strtoupper($expect);
    }

    public function isSsl(): bool
    {
        if (in_array($this->server('https', ''), ['1', 'on'])) return true;
        if ($this->server('request_scheme') == 'https') return true;
        if ($this->port() == 443) return true;
        if ($this->server('http_x_forwarded_proto') == 'https') return true;

        return false;
    }

    public function isCli(): bool
    {
        return strstr(php_sapi_name(), 'cli');
    }

    public function isCgi(): bool
    {
        return strstr(php_sapi_name(), 'cgi');
    }

    public function isAjax(): bool
    {
        $value = $this->server('http_x_requested_with', '');
        $result = strtolower($value) == 'xmlhttprequest';
        return $result ?: ($this->param($this->varAjax) ? true : false);
    }

    public function isPjax(): bool
    {
        $result = $this->server('http_x_pjax') ? true : false;
        return $result ?: ($this->param($this->varPjax) ? true : false);
    }

    public function isJson(): bool
    {
        return strpos($this->type(), 'json') !== false;
    }

    public function isMobile(): bool
    {
        if (stristr($this->server('HTTP_VIA', ''), "wap")) {
            return true;
        } elseif (strpos(strtoupper($this->server('HTTP_ACCEPT', '')), "VND.WAP.WML")) {
            return true;
        } elseif ($this->server('HTTP_X_WAP_PROFILE') || $this->server('HTTP_PROFILE')) {
            return true;
        } elseif (preg_match('/(blackberry|configuration\/cldc|hp |hp-|htc |htc_|htc-|iemobile|kindle|midp|mmp|motorola|mobile|nokia|opera mini|opera |Googlebot-Mobile|YahooSeeker\/M1A1-R2D2|android|iphone|ipod|mobi|palm|palmos|pocket|portalmmm|ppc;|smartphone|sonyericsson|sqh|spv|symbian|treo|up.browser|up.link|vodafone|windows ce|xda |xda_)/i', $this->server('HTTP_USER_AGENT', ''))) {
            return true;
        }

        return false;
    }

    //------------------------------------------------ get request info
    public function host(bool $strict = false): string
    {
        $host = $this->server('http_host', '') ?: $this->server('http_x_forwarded_host', '');

        if ($strict && strpos($host, ':')) {
            $host = strstr($host, ':', true);
        }
        return $host;
    }

    public function scheme(): string
    {
        return $this->isSsl() ? 'https' : 'http';
    }

    public function port(): int
    {
        return intval($this->server('server_port') ?? $this->server('http_x_forwarded_port'));
    }

    public function remotePort(): int
    {
        return intval($this->server('remote_port'));
    }

    public function protocol(): string
    {
        return $this->server('server_protocol', '');
    }


    public function contentType(bool $original = false): string
    {
        $contentType = $this->header('content_type', '');

        if (strpos($contentType, ';') > 0) {
            [$type] = explode(';', $contentType);
        } else {
            $type = $contentType;
        }
        $type = trim($type);

        return $original ? $type : strtolower($type);
    }

    public function domain(bool $decludePort = false): string
    {
        return $this->scheme() . '://' . $this->host($decludePort);
    }

    public function subDomain(): string
    {
        $host = $this->host(true);
        $rootDomain = $this->rootDomain();
        $subDomain = rtrim(strstr($host, $rootDomain, true), '.');
        return $subDomain;
    }

    public function rootDomain(): string
    {
        $host = $this->host(true);
        $items = explode('.', $host);
        $root = count($items) >= 2 ? array_pop($items) . '.' . array_pop($items) : array_pop($items);
        return $root;
    }

    public function url(bool $complete = false): string
    {
        $url = $this->server('http_x_rewrite_url | request_uri', '');

        if (!$url && $this->server('orig_path_info')) {
            $query = $this->query();
            $url = $this->server('orig_path_info') . ($query ? '?' . $query : '');
        }

        if (!$url && isset($_SERFVER['argv'][1])) {
            $url = $_SERVER['argv'][1];
        }

        return ($complete ? $this->host() : '') . $url;
    }

    public function baseUrl(bool $complete = false): string
    {
        $url = $this->url($complete);
        return strstr($url, '?', true) ?: $url;
    }

    public function query(): string
    {
        return $this->server('query_string', '');
    }

    public function baseFile(bool $complete = false): string
    {
        $baseFile = '';
        $scriptName = basename($this->server('script_filename'));
        $checkKeys = ['script_name', 'php_self', 'orig_script_name'];

        foreach ($checkKeys as $key) {
            if (basename($this->server($key, '')) === $scriptName) {
                $baseFile = $this->server($key);
                break;
            }
        }

        if (!$baseFile && ($pos = strpos($this->server('php_self', ''), '/' . $scriptName)) !== false) {
            $baseFile = substr($this->server('php_self'), 0, $pos) . '/' . $scriptName;
        }

        $documentRoot = $this->server('document_root', '');
        $scriptFilename = $this->server('script_filename', '');
        if (!$baseFile && $documentRoot && strpos($scriptFilename, $documentRoot) === 0) {
            $baseFile = str_replace($documentRoot, '', $scriptFilename);
            $baseFile = str_replace('\\', '/', $baseFile);
        }

        return ($complete ? $this->domain() : '') . $baseFile;
    }

    public function root(bool $complete = false): string
    {
        $file = $this->baseFile();
        if ($file && strpos($this->url(), $file) !== 0) {
            $file = dirname($file);
        }
        return ($complete ? $this->domain() : '') . $file;
    }

    public function pathinfo(): string
    {
        return rtrim($this->server('path_info|redirect_path_info', ''), '/');
    }

    public function ext(): string
    {
        return strtolower(pathinfo($this->pathinfo(), PATHINFO_EXTENSION));
    }

    public function time(bool $float = false)
    {
        $key = $float ? 'request_time_float' : 'request_time';
        return $this->server($key, 0);
    }

    public function type(): string
    {
        $type = '';
        $accept = $this->server('http_accept', '');

        if ($accept) {
            [$acceptStr] = explode(';', $accept);
            $acceptList = explode(',', $acceptStr);
            foreach ($this->mimeTypeList as $key => $mime) {
                foreach ($acceptList as $v) {
                    if (strstr($mime, $v) !== false) {
                        $type = $key;
                        break;
                    }
                }
                if ($type) break;
            }
        }

        return $type;
    }

    public function method(): string
    {
        return strtoupper($this->server('request_method', 'GET'));
    }


    //------------------------------------------------ get input variable

    /**
     * array $name:     [key1, key2] | [key1, key2=>default] | [key1, [key2, default]]
     */
    public function only(array $name, $data = 'param', $filter = '')
    {
        $value = [];
        $data = is_array($data) ? $data : $this->getDataFromSource($data);

        foreach ($name as $k => $v) {
            if (is_int($k)) {
                if (is_array($v)) {
                    [$key, $default] = array_merge($v, [null]);
                } else {
                    $key = $v;
                    $default = null;
                }
            } else {
                $key = $k;
                $default = $v;
            }
            $value[$key] = $this->getRequestInputData($data, $key, $default, $filter);
        }

        return $value;
    }

    public function param($name = null, $default = null, $filter = '')
    {
        $data = array_merge($this->get, $this->post, $this->input);
        return $this->getRequestInputData($data, $name, $default, $filter);
    }

    public function get($name = null, $default = null, $filter = '')
    {
        return $this->getRequestInputData($this->get, $name, $default, $filter);
    }

    public function post($name = null, $default = null, $filter = '')
    {
        return $this->getRequestInputData($this->post, $name, $default, $filter);
    }

    public function put($name = null, $default = null, $filter = '')
    {
        return $this->getRequestInputData($this->put, $name, $default, $filter);
    }

    public function delete($name = null, $default = null, $filter = '')
    {
        return $this->getRequestInputData($this->delete, $name, $default, $filter);
    }

    // filter: [*, '', success, error, jpg|png, success&png, error&jpg|jpeg]
    public function file($name = null, $filter = '*', ?array $default = null)
    {
        $res = null;
        $filter = strtolower($filter);
        $isSingleKey = false;
        if (is_null($name) || $name == '') {
            $res = $this->file;
        } else if (is_array($name)) {
            foreach ($name as $k) {
                $res[$k] = $this->file[$k] ?? $default;
            }
        } else if (is_string($name)) {
            $res = $this->file[$name] ?? $default;
            $isSingleKey = true;
        }

        $res = $this->filterFile($res, $filter, $isSingleKey);

        return $res;
    }

    public function input($name = null, $default = null, $filter = '')
    {
        return $this->getRequestInputData($this->input, $name, $default, $filter);
    }

    public function cookie($name = null, $default = null, $filter = '')
    {
        return $this->getRequestInputData($this->cookie, $name, $default, $filter);
    }

    public function session($name = null, $default = null, $filter = '')
    {
        return $this->getRequestInputData($this->session, $name, $default, $filter);
    }

    public function route(?string $name = null, $default = null, $filter = '')
    {
        return $this->getRequestInputData($this->route, $name, $default, $filter);
    }

    public function request($name = null, $default = null, $filter = '')
    {
        return $this->getRequestInputData($this->request, $name, $default, $filter);
    }

    public function env($name = null, $default = null, $filter = '')
    {
        return $this->getRequestInputData($this->env, $name, $default, $filter);
    }


    //------------------------------------------------ protected
    protected function init()
    {
        $this->server = $_SERVER;
        $this->collectRequestHeader();
        $this->collectRequestData();
        $this->parseRequestPath();
        $this->registerMethodCheckFn();
    }

    protected function collectRequestHeader()
    {
        $server = $this->server;
        $data = array_filter($server, function ($key) {
            return strstr($key, 'HTTP_');
        }, ARRAY_FILTER_USE_KEY);
        $data = array_change_key_case($data);
        $this->header = $data;
    }

    protected function collectRequestData()
    {
        $this->get = $_GET;
        $this->post = $_POST;
        $this->request = $_REQUEST;
        $this->env = $_ENV;
        $this->cookie = $_COOKIE;
        $this->file = $this->parseFiles();

        if (isset($_SESSION)) $this->session = $_SESSION;
        $input = $this->parseInputContent();
        $this->input = is_array($input) ? $input : [];

        $conType = $this->contentType();
        $method = strtolower($this->method());
        if (strstr($conType, 'json')) {
            if (in_array($method, ['post', 'put', 'delete'])) {
                $this->$method = array_merge($this->$method, $this->input);
            }
        }
    }

    protected function parseRequestPath()
    {
        $pathInfo = $this->pathinfo();
        $pathSlice = explode('/', trim($pathInfo, '/'));

        $controller = ($pathSlice[0] ?? '') ?: config('app.default_controller', '');
        $action = ($pathSlice[1] ?? '') ?: config('app.default_action', '');
        if (($pos = strrpos($action, '.' . $this->ext())) > 0) {
            $action = substr($action, 0, $pos);
        }

        $this->controller = $controller;
        $this->action = $action;
    }

    protected function parseInputContent()
    {
        $inputContent = file_get_contents('php://input');
        if (strstr($this->contentType(), 'json')) {
            $input = json_decode($inputContent, true);
        } else {
            parse_str($inputContent, $input);
        }
        return $input;
    }

    protected function parseFiles()
    {
        $files = [];
        foreach ($_FILES as $k => $file) {
            if (is_array($file['name'])) {
                $files[$k] = $files[$k] ?? [];
                for ($i = 0; $i < count($file['name']); $i++) {
                    $files[$k][$i] = [
                        'name' => $file['name'][$i],
                        'type' => $file['type'][$i],
                        'tmp_name' => $file['tmp_name'][$i],
                        'error' => $file['error'][$i],
                        'size' => $file['size'][$i],
                    ];
                }
            } else {
                $files[$k] = $file;
            }
        }
        return $files;
    }

    protected function registerMethodCheckFn()
    {
        $methodList = ['isGet', 'isPost', 'isPut', 'isDelete', 'isHead', 'isOptions', 'isTrace', 'isPatch'];
        $this->macro($methodList, function ($method) {
            $method = substr($method, 2);
            return $this->checkRequestMethod($method);
        });
    }

    protected function getRequestInputData($data, $name, $default, $filter = '')
    {
        if (is_null($name)) return $data;

        if (is_array($name)) {
            return $this->only($name, $data, $filter);
        }

        if (is_string($name)) {
            $names = strpos($name, '.') > 0 ? explode('.', $name) : [$name];
            while (empty($names) == false) {
                $key = array_shift($names);
                $data = $data[$key] ?? null;
                if (is_null($data)) break;
            }
            return $this->filterData($data ?? $default, $filter);
        } else if (is_numeric($name)) {
            return $this->filterData($data[$name] ?? $default, $filter);
        }

        return $default;
    }

    protected function getDataFromSource($source)
    {
        $dataSources = ['get', 'post', 'input', 'param', 'put', 'delete', 'cookie', 'server'];

        if (is_string($source)) {
            $source = strtolower($source);
            if (in_array($source, $dataSources) == false) {
                throw new \Exception('Request data source is not exists');
            }
            $data = $this->$source();
        } else if (is_array($source)) {
            $data = $source;
        } else {
            throw new \Exception('The type of data source is not allowed');
        }
        return $data;
    }

    protected function filterData($data, $filter = '')
    {
        if ($filter instanceof \Closure) {
            return $filter($data);
        }
        return $data;
    }

    protected function filterFile(?array $data, string $filter, bool $isSingleKey): ?array
    {
        if (is_null($data)) return $data;

        $res = null;
        if ($isSingleKey) {
            $res = $this->filterFileSingleField($data, $filter);
        } else {
            foreach ($data as $k => $v) {
                $res[$k] = $this->filterFileSingleField($v, $filter);
            }
        }

        return $res;
    }

    //------------------------------------------------ private
    private function filterFileSingleField(array $data, string $filter)
    {
        $res = null;
        $isMultiple = is_numeric(array_key_first($data));

        if ($isMultiple) {
            $res = [];
            foreach ($data as $file) {
                if ($this->validateFile($file, $filter)) $res[] = $file;
            }
        } else {
            if ($this->validateFile($data, $filter)) $res = $data;
        }

        return $res;
    }

    private function validateFile(array $file, string $validator)
    {
        if (in_array($validator, ['', '*'])) return true;

        // success, success&jpg, error, error&png|gif
        $error = -1;
        if (strpos($validator, 'success') === 0) $error = 0;
        if (strpos($validator, 'error') === 0) $error = 1;
        if (isset($file['error']) == false) return false;
        if ($error === 0 && $file['error'] !== 0) return false;
        if ($error === 1 && $file['error'] === 0) return false;

        // jpg|png...
        $validator = preg_replace('/success&?|error&?|\s+/', '', $validator);
        $allowTypes = array_filter(explode('|', $validator), 'strlen');
        $isTypeValid = false;
        if (empty($allowTypes)) {
            $isTypeValid = true;
        } else {
            foreach ($allowTypes as $type) {
                if (strstr($file['type'] ?? '', $type)) $isTypeValid = true;
            }
        }
        if ($isTypeValid == false) return false;

        return true;
    }
}
